package hongcaosp.app.android.video.player;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import java.util.ArrayList;
import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.comment.CommentFragment;
import hongcaosp.app.android.common.BaseAdapter;
import hongcaosp.app.android.common.IListView;
import hongcaosp.app.android.common.PresenterListener;
import hongcaosp.app.android.modle.bean.IUser;
import hongcaosp.app.android.modle.bean.IVideo;
import hongcaosp.app.android.user.UserDetailActivity;
import hongcaosp.app.android.video.ShareUI;
import hongcaosp.app.android.video.VisiblePage;
import xlj.lib.android.base.component.BaseActivity;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.ScreenUtils;
import xlj.lib.android.base.utils.StatusBarUtil;

public class VideosPlayActivity extends BaseActivity implements IListView<IVideo>, VideoHolder.VideoClickListener,VisiblePage {

    private RecyclerView recyclerView;

    private BaseAdapter<IVideo> videoPagerAdapter;
    private VideoHolder videoHolder;

    private PagerPlayerManager pagerPlayerManager;

    private MaterialRefreshLayout swipeRefreshLayout;

    private VideoPresenter videoPresenter;

    private LoadVideoProxy videoDataSource;
    private boolean showFull;
    private boolean isVisible;

    @Override
    protected void initData(Intent intent) {
        int type = intent.getIntExtra("type",0);
        int index = intent.getIntExtra("index",0);
        long userId = intent.getLongExtra("user_id",0);
        int number = intent.getIntExtra("number",0);
        String content = intent.getStringExtra("content");

        ArrayList<IVideo> videos = (ArrayList<IVideo>) intent.getSerializableExtra("videoList");
        videoDataSource = new LoadVideoProxy(this, type,number,userId);
        videoDataSource.setContent(content);

        videoPagerAdapter.setData(videos);
        videoPagerAdapter.notifyDataSetChanged();
        moveToPosition((LinearLayoutManager) recyclerView.getLayoutManager(),recyclerView,index);
    }



    @Override
    protected void initView() {
        StatusBarUtil.setStatusBarDarkTheme(this,false);

        Window window =  getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        showFull = ScreenUtils.getScreenHeight(this) * 9  <= 16 * ScreenUtils.getScreenWidth(this);

//        if (ScreenUtils.checkDeviceHasNavigationBar(this)) {
//            showFull = true;
//        }
        this.recyclerView = findViewById(R.id.recycler_view);
        swipeRefreshLayout = findViewById(R.id.swipe_fresh);

        videoPagerAdapter = new BaseAdapter<IVideo>() {
            @NonNull
            @Override
            public VideoHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                videoHolder  =new VideoHolder(LayoutInflater.from(VideosPlayActivity.this).inflate(R.layout.item_shortvideo,
                        parent, false), VideosPlayActivity.this, VideosPlayActivity.this);
                videoHolder.setVideoClickListener(VideosPlayActivity.this);
                videoHolder.setFillScreen(showFull);
                return videoHolder;
            }
        };
        pagerPlayerManager = new PagerPlayerManager(this.recyclerView,this);

        recyclerView.setAdapter(videoPagerAdapter);

        findViewById(R.id.comment_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommentFragment commentFragment = new CommentFragment();
                commentFragment.setVideo(videoHolder.getVideoPlayer());
                commentFragment.setOnCommentListener(new CommentFragment.OnCommentListener() {
                    @Override
                    public void onCommentCount() {
                        if (videoHolder != null) {
                            videoHolder.freshComment();
                        }
                    }
                });
                commentFragment.show(getSupportFragmentManager(),"");
            }
        });

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
        if (showFull) {
            lp.bottomMargin = 0;
        } else {
            lp.bottomMargin = (int) getResources().getDimension(R.dimen.tab_height);
        }
        swipeRefreshLayout.setLayoutParams(lp);

        videoPresenter = new VideoPresenter();

        swipeRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                if (videoDataSource != null) {
                    videoDataSource.freshData();
                }
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (videoDataSource != null) {
                    videoDataSource.loadMore();
                }
            }
        });
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_videos_play;
    }

    @Override
    public void freshList(List<IVideo> data, boolean canLoadMore) {
        videoPagerAdapter.setData(data);
        videoPagerAdapter.notifyDataSetChanged();
        swipeRefreshLayout.finishRefresh();
        swipeRefreshLayout.setLoadMore(canLoadMore);
    }

    @Override
    public void addList(List<IVideo> data, boolean canLoadMore) {
        videoPagerAdapter.addData(data);
        videoPagerAdapter.notifyDataSetChanged();
        swipeRefreshLayout.finishRefreshLoadMore();
        swipeRefreshLayout.setLoadMore(canLoadMore);
    }

    @Override
    protected void onResume() {
        super.onResume();
        PlayVideoManager.getInstance().onShow(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        isVisible = true;
        PlayVideoManager.getInstance().start(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        PlayVideoManager.getInstance().onHide(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isVisible = false;
        PlayVideoManager.getInstance().stop(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (videoHolder != null && videoHolder.playerView != null) {
            videoHolder.playerView.stopPlay();
            videoHolder.playerView.release();
        }
        Window window =  getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        PlayVideoManager.getInstance().destroy(this);
    }

    @Override
    public void onUserClick(IUser user) {
        UserDetailActivity.toDetail(this,user.getUserId());
    }

    @Override
    public void onShare(IVideo videoPlayer) {
        ShareUI shareUI = new ShareUI(this,videoPlayer);
        shareUI.show();
    }

    @Override
    public void onLike(final IVideo videoPlayer,final VideoHolder videoHolder) {
        if(videoPresenter != null) {
            videoPresenter.likeVideo(videoPlayer, new PresenterListener() {
                @Override
                public void onSuccess() {
                    videoHolder.freshLike();
                }

                @Override
                public void onFail(String message) {
                    ToastManager.getInstance().showToast(message);
                }
            });
        }
    }

    @Override
    public void unLike(final IVideo videoPlayer, final VideoHolder videoHolder) {
        if (videoPresenter != null) {
            videoPresenter.cancelikeVideo(videoPlayer, new PresenterListener() {
                @Override
                public void onSuccess() {
                    videoHolder.freshLike();
                }

                @Override
                public void onFail(String message) {
                    ToastManager.getInstance().showToast(message);
                }
            });
        }
    }

    @Override
    public void onFollow(IVideo videoPlayer, final VideoHolder videoHolder) {
        if (videoPresenter != null) {
            videoPresenter.followUser(videoPlayer.getAuthor(), new PresenterListener() {
                @Override
                public void onSuccess() {
                    videoHolder.freshUserFlag();
                }

                @Override
                public void onFail(String message) {
                    ToastManager.getInstance().showToast(message);
                }
            });
        }
    }

    @Override
    public void unFollow(IVideo videoPlayer, final VideoHolder videoHolder) {
        if (videoPresenter != null) {
            videoPresenter.cancelFollowUser(videoPlayer.getAuthor(), new PresenterListener() {
                @Override
                public void onSuccess() {
                    videoHolder.freshUserFlag();
                }

                @Override
                public void onFail(String message) {
                    ToastManager.getInstance().showToast(message);
                }
            });
        }
    }

    @Override
    public void onComment(IVideo videoPlayer, final VideoHolder videoHolder) {
        CommentFragment commentFragment = new CommentFragment();
        commentFragment.setVideo(videoPlayer);
        commentFragment.setOnCommentListener(new CommentFragment.OnCommentListener() {
            @Override
            public void onCommentCount() {
                if (videoHolder != null) {
                    videoHolder.freshComment();
                }
            }
        });
        commentFragment.show(getSupportFragmentManager(),"");
    }

    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager   设置RecyclerView对应的manager
     * @param mRecyclerView  当前的RecyclerView
     * @param n  要跳转的位置
     */
    public static void moveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }
    }

    public static void toPlayVideos(Context context,int type,ArrayList<IVideo> videos,int number,long userId,int index) {
        if (context != null) {
            Intent intent = new Intent(context,VideosPlayActivity.class);
            intent.putExtra("type",type);
            intent.putExtra("number",number);
            intent.putExtra("user_id",userId);
            if (videos != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("videoList", videos);
                intent.putExtras(bundle);
            }
            intent.putExtra("index",index);
            context.startActivity(intent);
        }
    }
    public static void toPlayVideos(Context context,int type,ArrayList<IVideo> videos,int number,int index,String content) {
        if (context != null) {
            Intent intent = new Intent(context,VideosPlayActivity.class);
            intent.putExtra("type",type);
            intent.putExtra("number",number);
            if (videos != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("videoList", videos);
                intent.putExtras(bundle);
            }
            intent.putExtra("content",content);
            intent.putExtra("index",index);
            context.startActivity(intent);
        }
    }

    @Override
    public boolean isVisible() {
        return isVisible;
    }
}
